package com.yuch.service;

import com.yuch.config.security.LoginUser;
import com.yuch.config.single.SingleMap;
import com.yuch.entity.User;
import com.yuch.utils.JwtUtil;
import com.yuch.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

/**
 * @projectName: springboot_31_ActiveMQ
 * @author: yuch
 * @description: TODO
 * @date: 2024/8/5 14:48
 */


@Service
public class LoginServcie {
    @Autowired
    private AuthenticationManager authenticationManager;
//    @Autowired
//    private RedisCache redisCache;


    public ResponseResult login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //返回的结果是不是已经比对过用户名和密码了？？？？？
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("用户名或密码错误");
        }
        //使用userid生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        //authenticate存入redis
//        redisCache.setCacheObject("login:"+userId,loginUser);
        //直接存储在内存里面
        SingleMap.getInstance().put("login:" + userId, loginUser);
        //把token响应给前端
        HashMap<String, String> map = new HashMap<>();
        map.put("token", jwt);
        return new ResponseResult(200, "登陆成功", map);
    }
}
